package com.hejielife.producerconsumer1;

/**
 * 2019年8月2日 下午1:48:53
 * 
 * @author hejielife
 * @despribe Table
 */
public class Table {
	private final String[] buffer;
	private int tail; // 消费者位置
	private int head; // 生产者位置
	private int count; // buffer 的cake多少

	public Table(int count) {
		this.buffer = new String[count];
		this.head = 0;
		this.tail = 0;
		this.count = 0;
	}

	// 添加cake
	public synchronized void put(String cake) throws InterruptedException {
		System.out.println(Thread.currentThread().getName() + " puts " + cake);
		while (count >= buffer.length) {
			System.out.println(Thread.currentThread().getName() + " wait BEGIN");
			wait();
			System.out.println(Thread.currentThread().getName() + " wait END");
		}
		buffer[tail] = cake;
		tail = (tail + 1) % buffer.length;
		count++;
		notifyAll();
	}

	// 取出cake
	public synchronized String take() throws InterruptedException {
		while (count <= 0) {
			System.out.println(Thread.currentThread().getName() + " wait BEGIN");
			wait();
			System.out.println(Thread.currentThread().getName() + " wait END");
		}
		String cake = buffer[head];
		head = (head + 1) % buffer.length;
		count--;
		notifyAll();
		System.out.println(Thread.currentThread().getName() + " takes " + cake);
		return cake;
	}
}
